import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { verifyToken } from '@/lib/auth'

export async function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl
  console.log(`[中间件] 处理路径: ${pathname}`)

  // 公开路径，不需要认证
  const publicPaths = ['/login', '/register', '/api/auth/login', '/api/auth/register', '/test-login', '/simple-login', '/html-login', '/test-tikhub', '/api/test-tikhub']

  // 如果是公开路径，直接通过
  if (publicPaths.some(path => pathname.startsWith(path))) {
    console.log(`[中间件] 公开路径，直接通过: ${pathname}`)
    return NextResponse.next()
  }

  // 检查认证状态
  const allCookies = request.cookies.getAll()
  console.log(`[中间件] 所有cookies:`, allCookies.map(c => `${c.name}=${c.value.substring(0, 20)}...`))

  const token = request.cookies.get('auth-token')?.value
  console.log(`[中间件] 路径=${pathname}, 有token=${!!token}`)

  if (token) {
    console.log(`[中间件] Token前20字符: ${token.substring(0, 20)}...`)
  }

  if (!token) {
    console.log('[中间件] 没有token，重定向到登录页')
    // 如果是API请求，返回401
    if (pathname.startsWith('/api/')) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }

    // 如果是页面请求，重定向到登录页
    return NextResponse.redirect(new URL('/login', request.url))
  }

  // 验证token
  console.log(`[中间件] 开始验证token...`)
  const user = await verifyToken(token)
  console.log(`[中间件] Token验证结果:`, user ? `用户${user.username}` : '验证失败')

  if (!user) {
    console.log(`[中间件] Token无效，清除cookie并重定向`)
    // token无效，清除cookie并重定向
    const response = pathname.startsWith('/api/')
      ? NextResponse.json({ error: '认证已过期' }, { status: 401 })
      : NextResponse.redirect(new URL('/login', request.url))

    response.cookies.set('auth-token', '', {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: 0
    })

    return response
  }

  // 认证通过，继续请求
  return NextResponse.next()
}

export const config = {
  matcher: [
    /*
     * 匹配所有请求路径，除了:
     * - api/auth/* (认证相关API)
     * - _next/static (静态文件)
     * - _next/image (图片优化)
     * - favicon.ico (网站图标)
     * - public文件夹中的文件
     */
    '/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
  ],
  runtime: 'nodejs'
}
